<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, pageUsersApi, selRolesApi, treeDictsApi, saveUserApi, oneUserApi, proUsersApi } from '@/commons/api'
import routes from '@/commons/router'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager.vue'
import TreeSel from '@/components/cascader/TreeSel.vue'
import Selector from '@/components/select/Selector.vue'
import { CScrollbar } from 'c-scrollbar'
import Loader from '@/components/loader/Loader.vue'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false,
  pasAuth: false,
  unpAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      procAuth.value = {
        addAuth: userBtnCode.indexOf('1001010501') !== -1,
        delAuth: userBtnCode.indexOf('1001010502') !== -1,
        edtAuth: userBtnCode.indexOf('1001010503') !== -1,
        pasAuth: userBtnCode.indexOf('1001010504') !== -1,
        unpAuth: userBtnCode.indexOf('1001010505') !== -1
      }
      await list(0, 1)
      await selRole('')
      await selDept()
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const schObj = {
  keywords: '',
  deptId: '',
  deptName: '',
  deptCode: '',
  roleId: '',
  roleName: '',
  roleCode: '',
  states: 0,
  stateName: '',
  stateCode: '',
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const userList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageUsersApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    userList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    keywords: '',
    deptId: '',
    deptName: '',
    deptCode: '',
    roleId: '',
    roleName: '',
    roleCode: '',
    states: 0,
    stateName: '',
    stateCode: '',
    offset: 0,
    limit: 20
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    userList.value.forEach(item => {
      idList.value.push(item.userId)
      checkList.value.push(true)
    })
  } else {
    userList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, userId) => {
  if(!checkList.value[idx]) {
    idList.value.push(userId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === userId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const userObj = {
  userId: '',
  usname: '',
  passwd: '',
  nickName: '',
  mobile: '',
  deptId: '',
  deptName: '',
  deptCode: '',
  roleId: '',
  roleName: '',
  roleCode: '',
  kind: 1
}
const userForm = ref(userObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (userId) => {
  loadShow.value = true
  try {
    const res = await oneUserApi({userId})
    loadShow.value = false
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      showModal.value = true
      userForm.value = res.data
    } else {
      Msg({ kind: 'info', txt: '暂无内容' })
    }
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统异常，请稍后再试！' + e })
  }
}
// save 保存提交
const save = async () => {
  let userId = userForm.value.userId
  let usname = userForm.value.usname
  let passwd = userForm.value.passwd
  let nickName = userForm.value.nickName
  let mobile = userForm.value.mobile
  let deptId = userForm.value.deptId
  let roleId = userForm.value.roleId
  if(usname === '' || usname.length > 50) {
    Msg({ kind: 'warn', txt: '用户的昵称不能为空，且长度不超过50个字符！' })
    return
  } else if((userId==='' && (passwd==='' || passwd.length<6 || passwd.length>30)) || (userId!=='' && passwd!=='' && (passwd.length<6 || passwd.length>30))) {
    Msg({ kind: 'warn', txt: '用户的登录密码不能为空，且长度为6至30位！' })
    return
  } else if(nickName === '' || nickName.length > 50) {
    Msg({ kind: 'warn', txt: '用户昵称不能为空，且长度不超过50个字符！' })
    return
  } else if(mobile === '' || mobile.length !== 11) {
    Msg({ kind: 'warn', txt: '手机号码不能为空，且长度为11个字符！' })
    return
  } else if(deptId === '' || deptId.length !== 21) {
    Msg({ kind: 'warn', txt: '用户所属部门不能为空！' })
    return
  } else if(roleId === '' || roleId.length !== 21) {
    Msg({ kind: 'warn', txt: '用户角色不能为空！' })
    return
  }
  loadShow.value = true
  try {
    const res = await saveUserApi(userForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，用户信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  userForm.value = {
    userId: '',
    usname: '',
    passwd: '',
    nickName: '',
    mobile: '',
    roleId: '',
    roleName: '',
    roleCode: '',
    deptId: '',
    deptName: '',
    deptCode: '',
    kind: 1
  }
}

// process 删除用户
const process = (states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要删除选中的用户吗？').then(() => {
    procUsers(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// procUsers 删除用户实现，分离出来防止调用时异步报错
const procUsers = async (states) => {
  let userIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proUsersApi({ userIds, states })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，用户操作成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const roleList = ref([])
const selRole = async (keywords) => {
  roleList.value = []
  const res = await selRolesApi({keywords: keywords})
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    roleList.value = res.data
  }
}

const selByKey = (keywords) => {
  selRole(keywords)
}

// selDept 获取部门下拉列表
const deptList = ref([])
const selDept = async () => {
  const res = await treeDictsApi({ kind: 2, typeCode: 'SYS_DEPT' })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    deptList.value = res.data
  }
}

const stateList = ref([{selId: 1, selName: '已启用', selCode: '101', chked: false}, {selId: 3, selName: '已停用', selCode: '103', chked: false}])

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.roleId = item.selId
      schRef.value.roleName = item.selName
      schRef.value.roleCode = item.selCode
      break
    case 2:
      userForm.value.roleId = item.selId
      userForm.value.roleName = item.selName
      userForm.value.roleCode = item.selCode
      break
    case 3:
      schRef.value.deptId = item.selId
      schRef.value.deptName = item.selName
      schRef.value.deptCode = item.selCode
      break
    case 4:
      userForm.value.deptId = item.selId
      userForm.value.deptName = item.selName
      userForm.value.deptCode = item.selCode
      break
    case 5:
      schRef.value.states = item.selId
      schRef.value.stateName = item.selName
      schRef.value.stateCode = item.selCode
      break
  }
}

// fmtState 状态转码
const fmtState = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '已启用'
        break;
      case 3:
        str = '已停用'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <div class="b">
      <div class="c">
        <div v-if="procAuth.addAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="procAuth.delAuth" class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div v-if="procAuth.pasAuth" class="btn-ds mr15" title="启用" @click="process(1)"><i class="iconfont">&#xea30;</i> 启用</div>
        <div v-if="procAuth.unpAuth" class="btn-dw mr15" title="停用" @click="process(3)"><i class="iconfont">&#xea2e;</i> 停用</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 系统管理 > 用户管理</div>
    </div>
    <div v-show="schShow" class="e">
      <div class="mr15 mt10"><tree-sel :kind="3" :tree-list="deptList" :inboxed="true" :curName="schRef.deptName!=='' ? schRef.deptName+'['+schRef.deptCode+']' : ''" pre-name="部门" @setValue="setValue" /></div>
      <div class="mr15 mt10"><selector :kind="1" :sel-list="roleList" :inboxed="true" :cur-name="schRef.roleName ? schRef.roleName + '[' + schRef.roleCode + ']' : ''" pre-name="角色" @setValue="setValue" @selByKey="selByKey" /></div>
      <div class="mr15 mt10"><selector :kind="5" :sel-list="stateList" :inboxed="true" :cur-name="schRef.stateName ? schRef.stateName + '[' + schRef.stateCode + ']' : ''" pre-name="状态" @setValue="setValue" /></div>
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="f mt10">
        <div class="btn-pi mr15" title="搜索" @click="list(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 5%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 15%;">昵称</th>
            <th style="width: 15%;">账号</th>
            <th style="width: 15%;">手机号</th>
            <th style="width: 15%;">部门</th>
            <th style="width: 15%;">角色</th>
            <th style="width: 10%;">状态</th>
            <th style="width: 10%;">操作</th>
          </tr>
          <tr v-for="(curUser, index) in userList" :key="curUser.userId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, curUser.userId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td class="txt-center">{{curUser.nickName}}</td>
            <td class="txt-center">{{curUser.usname}}</td>
            <td class="txt-center">{{curUser.mobile}}</td>
            <td class="txt-center">{{curUser.deptName}}</td>
            <td class="txt-center">{{curUser.roleName}}</td>
            <td class="txt-center"><span :class="[curUser.states===1 ? 'tag-s' : 'tag-e']">{{fmtState(curUser.states)}}</span></td>
            <td class="txt-center">
              <span v-if="procAuth.edtAuth" class="cl-warn" title="修改" @click="update(curUser.userId)"><i class="iconfont">&#xea48;</i> 修 改</span>
            </td>
          </tr>
        </tbody>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 800px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存用户信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>用户昵称</div>
                <div><input type="text" v-model="userForm.nickName" maxlength="50" placeholder="请输入用户名称" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>登录账号</div>
                <div><input type="text" v-model="userForm.usname" maxlength="50" placeholder="请输入登录账号" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>登录密码</div>
                <div><input type="text" v-model="userForm.passwd" maxlength="30" placeholder="请输入登录密码，修改时为空则不改密码" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>手机号码</div>
                <div><input type="text" v-model="userForm.mobile" maxlength="11" placeholder="手机号码" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>所属部门</div>
                <tree-sel :tree-list="deptList" :kind="4" :inboxed="false" :curName="userForm.deptName ? userForm.deptName+'['+userForm.deptCode+']' : ''" pre-name="所属部门" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>用户角色</div>
                <selector :kind="2" :sel-list="roleList" :inboxed="false" :cur-name="userForm.roleName!=='' ? userForm.roleName+'['+userForm.roleCode+']' : ''" pre-name="角色" @setValue="setValue" @selByKey="selByKey" />
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.a {padding: 10px;}
.b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.c {display: inline-flex; display: -webkit-inline-flex;}
.d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.f {display: inline-flex; display: -webkit-inline-flex;}
</style>